<template>
  <!--绘制弹窗-->
  <el-dialog title="角色授权" :visible.sync="dialogShow" @close="dialogClose">
    <!--渲染权限树-->
    <el-tree
      ref="tree"
      node-key="id"
      :data="authList"
      :props="{label:'name'}"
      :default-checked-keys="checkedAuth"
      show-checkbox
      :check-strictly="true"
    />
    <el-row type="flex" justify="center" style="margin-top:20px">
      <el-button @click="dialogShow = false">取消</el-button>
      <el-button type="primary" @click="saveAuth">保存</el-button>
    </el-row>
  </el-dialog>
</template>

<script>
import { getPermissionListApi } from '@/api/permission'
import { tranListToTreeData } from '@/utils'
import { getRoleInfoApi, saveRoleAuthApi } from '@/api/setting'

export default {
  name: 'SetAuth',
  data() {
    return {
      dialogShow: false,
      authList: [], // 权限列表
      checkedAuth: [], // 选中的权限
      roleId: null // 角色id
    }
  },
  methods: {
    // 获取所有权限
    async getAllAuthList() {
      const res = await getPermissionListApi()
      // console.log(res)
      this.authList = tranListToTreeData(res, '0')
    },
    // 获取当前角色信息
    async getCurrentRoleInfo(id) {
      this.roleId = id
      const res = await getRoleInfoApi(id)
      console.log(res)
      this.checkedAuth = res.permIds
    },
    // 保存权限
    async saveAuth() {
      const permIds = this.$refs.tree.getCheckedKeys()
      if (permIds.length === 0) return this.$message.error('请选择权限')
      await saveRoleAuthApi({
        id: this.roleId,
        permIds
      })
      this.$message.success('保存成功')
      this.$emit('updateList')
      this.dialogShow = false
    },
    // 弹窗关闭事件
    dialogClose() {
      this.roleId = null
      this.checkedAuth = []
    }
  }
}
</script>

<style scoped>

</style>
